<template>
  <el-dialog title="修改密码" :visible.sync="visible" :append-to-body="true" :closeOnClickModal="false">
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="80px"
    >
      <el-form-item label="原密码" prop="password">
        <el-input type="password" v-model="dataForm.password"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input type="password" v-model="dataForm.newPassword"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input type="password" v-model="dataForm.confirmPassword"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="mail">
        <el-input type v-model="dataForm.mail"></el-input>
        <el-button
          type="success"
          plain
          @click="sendMail()"
          :loading="isload"
          :disabled="!show"
        >发送验证码</el-button>&nbsp
        <el-tag type="info" v-if="!show">还剩{{ count }}秒</el-tag>
      </el-form-item>

      <el-form-item label="验证码" prop="vercode">
        <el-input v-model="dataForm.vercode"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { clearLoginInfo } from '@/utils';
export default {
  data() {
    var validateConfirmPassword = (rule, value, callback) => {
      if (this.dataForm.newPassword !== value) {
        callback(new Error('确认密码与新密码不一致'));
      } else {
        callback();
      }
    };
    return {
      show: true,
      count: '', // 验证码倒计时
      timer: null,

      isload: false,
      visible: false,
      dataForm: {
        password: '',
        newPassword: '',
        confirmPassword: '',
        mail: '',
        vercode: '',
      },
      dataRule: {
        password: [{ required: true, message: '原密码不能为空', trigger: 'blur' }],
        newPassword: [
          { required: true, message: '新密码不能为空', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '密码长度在 6 到 15 个字符',
            trigger: 'blur',
          },
        ],
        confirmPassword: [
          { required: true, message: '确认密码不能为空', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' },
        ],
        mail: [
          {
            required: true,
            message: '邮箱地址不能为空,找回密码需要',
            trigger: 'blur',
          },
          {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur', 'change'],
          },
        ],
      },
    };
  },
  computed: {
    userName: {
      get() {
        return this.$store.state.user.name;
      },
    },
  },
  methods: {
    // 初始化
    init() {
      this.visible = true;
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields();
      });
    },
    //发送邮件验证码
    sendMail() {
      if (this.dataForm.mail != '' && this.dataForm.mail != null) {
        this.isload = true;
        var userType = this.$cookie.get('userType');
        this.$http({
          url: this.$http.adornUrl(`/edu-oss/sendMail/${userType}/${this.$store.state.user.id}/${this.dataForm.mail}`),
          methods: 'get',
        }).then((data) => {
          this.isload = false;
          if (data.data.code == 20000) {
            this.Countdown();
          } else {
            this.$message.error(data.data.message);
          }
        });
      }
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          var userType = this.$cookie.get('userType');
          var URLPATH = '';
          if (userType == 'student') {
            URLPATH = '/edu-student/updateInfo';
          }
          if (userType == 'teacher') {
            URLPATH = '/edu-teacher/updateInfo';
          }
          this.$http({
            url: this.$http.adornUrl(URLPATH),
            method: 'post',
            data: this.$http.adornData({
              username: this.$store.state.user.id,
              pwd: this.dataForm.password,
              newpwd: this.dataForm.newPassword,
              code: this.dataForm.vercode,
              // newPassword: this.dataForm.newPassword,
              // vercode: this.dataForm.vercode,
            }),
          }).then(({ data }) => {
            if (data && data.code == 20000) {
              this.$message({
                message: '修改密码成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$nextTick(() => {
                    clearLoginInfo();
                    this.$router.replace({ name: 'login' });
                  });
                },
              });
            }
            if (data && data.code == 40001) {
              this.$message.error('原密码输入错误！');
            }
            if (data && data.code == 40002) {
              this.$message.error('验证码输入错误！');
            }
          });
        }
      });
    },
    Countdown() {
      const TIME_COUNT = 90;
      if (!this.timer) {
        this.count = TIME_COUNT;
        this.show = false;
        this.timer = setInterval(() => {
          if (this.count > 0 && this.count <= TIME_COUNT) {
            this.count--;
          } else {
            this.show = true;
            clearInterval(this.timer);
            this.timer = null;
          }
        }, 1000);
      }
    },
  },
};
</script>

